package com.jzo2o.customer.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.publics.SmsCodeApi;
import com.jzo2o.common.constants.UserType;
import com.jzo2o.common.enums.SmsBussinessTypeEnum;
import com.jzo2o.common.expcetions.BadRequestException;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.customer.mapper.ServeProviderMapper;
import com.jzo2o.customer.model.domain.ServeProvider;
import com.jzo2o.customer.model.dto.request.InstitutionRegisterReqDTO;
import com.jzo2o.customer.service.IServeProviderService;
import com.jzo2o.customer.service.RegisterService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class RegisterServiceImpl extends ServiceImpl<ServeProviderMapper, ServeProvider> implements RegisterService {
    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private SmsCodeApi smsCodeApi;

    @Resource
    private IServeProviderService serveProviderService;

    @Resource
    private AgencyCertificationServiceImpl agencyCertificationService;

    @Override
    public void register(InstitutionRegisterReqDTO reqDTO) {
        //先判断传入的参数对象是否为空
        if (reqDTO == null) {
            throw new ForbiddenOperationException("请求参数异常!!");
        }

        //远程调用publics服务校验验证码是否正确
        boolean verifyResult = smsCodeApi.verify(reqDTO.getPhone(), SmsBussinessTypeEnum.INSTITION_REGISTER, reqDTO.getVerifyCode()).getIsSuccess();
        if (!verifyResult) {
            throw new BadRequestException("验证码错误，请重新获取");
        }

        //判断机构账号是否已注册
        Integer count = lambdaQuery()
                .eq(ServeProvider::getPhone, reqDTO.getPhone())
                .eq(ServeProvider::getType, UserType.INSTITUTION)
                .count();

        if (count > 0) {
            throw new ForbiddenOperationException("该账号已进行服务机构注册,请勿重复注册!!");
        }

        //保存用户账号信息
        // 自动注册
        serveProviderService.add(reqDTO.getPhone(), UserType.INSTITUTION, passwordEncoder.encode(reqDTO.getPassword()));

    }

}
